import { defineStore } from 'pinia'
import { getToken, setToken, removeToken } from "@/utils/request/auth"
import { login } from "@/api/login"

export const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken()
  }),
  actions: {
    // 登录
    login(userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid).then(res => {
          setToken(res.token)
          this.token = res.token
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    logOut() {
      return new Promise((resolve, reject) => {
        this.token = ''
        removeToken()
        resolve()
      })
    }
  }
})
